//
//  CategoryArtist.swift
//  MusicApp
//
//  Created by tianjs on 2023/4/21.
//

import SwiftUI

struct CategoryArtist: View {
    @State var date = Date()
    var body: some View {
        VStack {
            Text("SwiftUI封装UIKit之UIPicker")
            UDatePicker(date: self.$date)
        }
    }
}

struct CategoryArtist_Previews: PreviewProvider {
    static var previews: some View {
        CategoryArtist()
    }
}

struct UDatePicker: UIViewRepresentable {
    @Binding var date: Date
    
    private let datePicker = UIDatePicker()
    
    func makeUIView(context: Context) -> UIDatePicker {
        datePicker.datePickerMode = .dateAndTime
//        datePicker.datePickerStyle = .m
        datePicker.addTarget(context.coordinator, action: #selector(Coordinator.changed(_:)), for: .valueChanged)
        return datePicker
    }
    
    func updateUIView(_ uiView: UIDatePicker, context: Context) {
        datePicker.date = date
    }
    
    func makeCoordinator() -> UDatePicker.Coordinator {
        Coordinator(date: $date)
    }
    
    class Coordinator: NSObject {
        private let date: Binding<Date>
        
        init(date: Binding<Date>) {
            self.date = date
        }
        
        @objc func changed(_ sender: UIDatePicker) {
            self.date.wrappedValue = sender.date
        }
    }
}
